package com.itic.mall.mobile.base;



import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.applications.sys.sysexception.persistence.model.SysException;
import com.itic.appbase.applications.sys.sysexception.service.SysExceptionService;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.PropertyGetter;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecord;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample.Criteria;
import com.itic.mall.system.hongbaorecord.service.HongbaoRecordService;
import com.itic.mall.system.jifeng.persistence.model.Jifeng;
import com.itic.mall.system.malltoken.persistence.model.MallToken;
import com.itic.mall.system.malltoken.service.MallTokenService;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.marketuserproduct.persistence.model.MarketUserProduct;
import com.itic.mall.system.marketuserproduct.persistence.model.MarketUserProductExample;
import com.itic.mall.system.marketuserproduct.service.MarketUserProductService;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.persistence.model.OrderExample;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderjd.service.OrderJdService;
import com.itic.mall.system.orderpay.persistence.model.OrderPay;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.phonecode.persistence.model.PhoneCode;
import com.itic.mall.system.phonecode.persistence.model.PhoneCodeExample;
import com.itic.mall.system.phonecode.service.PhoneCodeService;
import com.itic.mall.system.premoney.persistence.model.PreMoney;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.service.ProductJdService;
import com.itic.mall.system.productjdstatis.persistence.model.ProductJdStatis;
import com.itic.mall.system.productjdstatis.persistence.model.ProductJdStatisExample;
import com.itic.mall.system.productjdstatis.service.ProductJdStatisService;
import com.itic.mall.system.productsku.persistence.model.ProductSku;
import com.itic.mall.system.productsku.service.ProductSkuService;
import com.itic.mall.system.synctgw.persistence.model.SyncTgw;
import com.itic.mall.system.synctgw.service.SyncTgwService;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.user.persistence.model.MallUserExample;
import com.itic.mall.system.user.service.MallUserService;


public class BaseMobileInterface
     extends BaseController {
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
	@Autowired
    protected SysSettingService sysSettingService;
	@Autowired
    protected MallTokenService mallTokenService;
	@Autowired
    protected MallUserService mallUserService;
	@Autowired
	protected PhoneCodeService phoneCodeService;
	@Autowired
	protected SysExceptionService sysExceptionService;
	@Autowired
	protected HongbaoRecordService hongbaoRecordService;
	@Autowired
	protected ProductService productService;
	@Autowired
	protected ProductSkuService productSkuService;
	@Autowired
	protected OutCommonService outCommonService;
	@Autowired
	protected OrderService orderService;
	@Autowired
	protected OrderJdService orderJdService;
	@Autowired
	protected OrderProductsService orderProductsService;
	@Autowired
	protected MarketUserService marketUserService;
	@Autowired
	protected MarketUserProductService marketUserProductService;
	@Autowired
	protected ProductJdService productJdService;
	@Autowired
	protected ProductJdStatisService productJdStaticService;
	@Autowired
	protected SyncTgwService syncTgwService;
	
	
	protected static final String ORG_CODE = "unknown";
	protected static final String CREATE_USER = "unknown";
	
	//接口返回键
    protected static final String RESULT = "result";
    protected static final String DATA = "data";
    protected static final String ERROR_CODE = "errorCode";
    protected static final String ERROR_MSG = "errorMsg";
    //接口返回值
    protected static final String SUCCESS = "success";
    protected static final String FAIL = "fail";
    protected static final String LOGIN = "login";
    
    protected static final String SUCCESS_ERROR_CODE = "0";//服务器异常
    protected static final String SERVER_ERROR_CODE = "1";//服务器异常
    protected static final String PARAM_ERROR_CODE = "2";//参数不正确
    protected static final String LOGIN_ERROR_CODE = "3";//用户未登入
    protected static final String PHONE_CODE_ERROR_CODE = "4";//验证码无效
    protected static final String PRODUCT_EMPTY_ERROR_CODE = "5";//验证码无效
    protected static final String TOKEN_ERROR_CODE = "6";//TOKEN无效
    protected static final String OPENID_ERROR_CODE = "7";//OPENID无效
    protected static final String UNIONID_ERROR_CODE = "8";//UNIONID 无效 
    protected static final String INVITING_ERROR_CODE ="9";//用户邀请码无效
    protected static final String STORE_CODE_ERROR_CODE = "10";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_CODE = "11";//商品ID无效
    protected static final String NOTICE_ID_ERROR_CODE = "12";//商品ID无效
    protected static final String LESS_MONEY_ERROR_CODE = "13";//
    protected static final String NONE_EXPRESS_ERROR_CODE = "14";//
    protected static final String ORDER_NULL_ERROR_CODE = "15";//
    protected static final String LINGQUED_ERROR_CODE = "16";
    protected static final String JD_PRODUCT_EXPIRED_ERROR_CODE = "17";
    protected static final String PRODUCT_NULL_ERROR_CODE = "18";
    protected static final String SKU_NULL_ERROR_CODE = "19";
    protected static final String WEIXIN_AUTH_ERROR_CODE = "20";
    protected static final String MARKET_EMPTY_ERROR_CODE = "21";
    protected static final String ADDRESS_EMPTY_ERROR_CODE = "22";
    protected static final String HONGBAO_EXPIRED_ERROR_CODE = "23";
    protected static final String NOT_ONE_ORDER_ERROR_CODE = "24";
    protected static final String ADDRESS_MAIN_ERROR_CODE = "25";
    protected static final String TGWID_ERROR_CODE = "26";
    
    protected static final String SUCCESS_ERROR_MSG = "请求成功！";//服务器异常
    protected static final String SERVER_ERROR_MSG = "服务器繁忙，请重试！";//服务器异常
    protected static final String PARAM_ERROR_MSG = "参数不正确，请检查！";//参数不正确
    protected static final String LOGIN_ERROR_MSG = "登入过期，请重新登入！";//用户未登入
    protected static final String PHONE_CODE_ERROR_MSG = "验证码无效！";//验证码无效
    protected static final String PRODUCT_EMPTY_ERROR_MSG = "商品数量不能为空!";//验证码无效
    protected static final String TOKEN_ERROR_MSG = "token无效!";//验证码无效
    protected static final String OPENID_ERROR_MSG = "openid无效!";//验证码无效
    protected static final String UNIONID_ERROR_MSG = "登入过期，请重新登入！";//验证码无效
    protected static final String INVITING_ERROR_MSG = "邀请码无效！";//注册成为商家的邀请码无效
    protected static final String STORE_CODE_ERROR_MSG = "店铺的代码无效！";//店铺的代码无效
    protected static final String PRODUCT_ID_ERROR_MSG ="商品ID无效！";//商品ID无效
    protected static final String NOTICE_ID_ERROR_MSG ="公告ID无效！";//商品ID无效
    protected static final String LESS_MONEY_ERROR_MSG ="用户金额不足！";//商品ID无效
    protected static final String NONE_EXPRESS_ERROR_MSG = "暂未有物流信息！";//物流为空
    protected static final String ORDER_NULL_ERROR_MSG = "订单无效！";//物流为空
    protected static final String LINGQUED_ERROR_MSG = "您已经领取过了！";
    protected static final String SKU_NULL_ERROR_MSG = "没有找到相应款式！";
    protected static final String PRODUCT_NULL_ERROR_MSG = "未找到商品！";
    protected static final String JD_PRODUCT_EXPIRED_ERROR_MSG = "京东商品已过期！";
    protected static final String WEIXIN_AUTH_ERROR_MSG = "需要微信授权登入！";
    protected static final String MARKET_EMPTY_ERROR_MSG = "未找到店铺信息！";
    protected static final String ADDRESS_EMPTY_ERROR_MSG = "未找到地址信息！";
    protected static final String HONGBAO_EXPIRED_ERROR_MSG = "红包未到领取时间！";
    protected static final String NOT_ONE_ORDER_ERROR_MSG = "您不是新手啦！";
    protected static final String ADDRESS_MAIN_ERROR_MSG = "默认地址不能删除！";
    protected static final String TGWID_ERROR_MSG = "您还没有建立推广位，是否立即创建?";
    
    //订单状态
    protected static final String NO_PAY = "noPay";//是否支付 
    protected static final String NO_FEEDBACK = "noFeedback";//是否评价
    protected static final String NO_FAHUO = "noFahuo";
    protected static final String NO_COMFIRM = "noConfirm";//是否确认收货
    protected static final String COMEBACK = "comeback";//退换货
    
    //public void log( Exception e ){
    	
    //}
    
    /**
     * 异常日志
     * @param e
     */
    public void logException( String className, String methodName, String message, String desc, Exception e ){
    	try{  
    	   Date now = new Date();
		   String nowString = DateHelper.formatDateTime(now);
		   
		   SysException exception = new SysException();
		   exception.setId(IdGen.uuid());
		   exception.setExceptionClass(className);
		   exception.setExceptionMethod(methodName);
		   
		   //exception.setExceptionNote();
		   exception.setExceptionNote(desc);
		   
		   exception.setExceptionTime(nowString);
		   
		   exception.setExceptionMessage(message);
		   
		   StringBuffer bf = new StringBuffer();
		   bf.append(FileHelper.getRootDir());
		   bf.append("exception");
		   bf.append(File.separator);
		   bf.append(DateHelper.getDateStringByDate(new Date(), "yyyy-MM-dd"));
		   bf.append(File.separator);
		   String filePath = bf.toString();
		   File f=new File(filePath);
		   if(!f.exists()){
		    	 f.mkdirs();
		   }
		   bf.append(IdGen.uuid());
           bf.append(".txt");
           filePath = bf.toString();
		   File tempfile =new File(filePath);
		   if(!tempfile.exists()){
		    	tempfile.createNewFile();
		   }
         
		   //输出一个错误日志文件
		   FileOutputStream out = new FileOutputStream(filePath);//确认流的输出文件和编码格式，此过程创建了“test.txt”实例
			
		   PrintStream printStream = new PrintStream(out);
		   e.printStackTrace(printStream);
		   out.close();
		   String replace = filePath.replace(FileHelper.getRootDir(), "");
		   //保存全路径
		   exception.setExceptionFilepath(PropertyGetter.getString("app.download.path") +"mall_fileupload/"+ replace);
		   sysExceptionService.add(exception);
		   
    	}catch(Exception temp){
		   temp.printStackTrace();
	    }
    }

    /**
     * 是否跨域方法
     * @param response
     * @return
     */
    public HttpServletResponse isCrrossDomain( HttpServletResponse response ){
    	//是否允许跨域
    	String isCrrossDomain = sysSettingService.getByKey("IS_CRROSS_DOMAIN");
    	String isSetCrrossDomain = PropertyGetter.getString("app.is.crross.domain");
    	if( isSetCrrossDomain.equals( isCrrossDomain ) ){
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
    	}
    	return response;
    }
    
    
    /**
     * 获取随机TOKEN方法
     */
    public String getToken(){
    	String orderNumber = RandomOrderNumHelper.getOrderNumber();
    	String uuid = IdGen.uuid();
    	return orderNumber + uuid;
    }
    
    /**
     * 获取 Token的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeToken(Date date){
    	String dayStr = "7";//默认TOKEN有效期为7天
    	String daySet =sysSettingService.getByKey("TOKEN_EXPIRED_DAY");
    	if( StringHelper.isNotBlank(daySet) ){
    		dayStr = daySet;
    	}
    	Date dateAfter = CalendarHelper.getDateAfter(date, Integer.parseInt(dayStr));
    	return dateAfter;
    }
    
    /**
     * 获取 验证码的过期 时间
     * @param date
     * @return
     */
    public Date getExpiredTimeCode(Date date){
    	String minuteStr = "5";//默认CODE有效期为5分
    	String minuteSet =sysSettingService.getByKey("CODE_EXPIRED_MINUTE");
    	if( StringHelper.isNotBlank(minuteSet) ){
    		minuteStr = minuteSet;
    	}
    	Date dateAfter = CalendarHelper.getMinuteAfter(date, Integer.parseInt(minuteStr));
    	return dateAfter;
    }
    
    /**
     * 获取当前版本信息
     * @return
     */
    public String getVersionMsg(){
    	String versionStr = "1.0.0";//默认CODE有效期为5分
    	String versionSet =sysSettingService.getByKey("VERSION_CURRENT");
    	if( StringHelper.isNotBlank(versionSet) ){
    		versionStr = versionSet;
    	}
    	return versionStr;
    }
    
    /**
     * 根据TOKEN获得用户,同时验证token的有效期
     * @return
     */
    public MallUser getMallUserByToken( String token ){
    	MallUser user = null;
    	MallToken mallTokenByToken = mallTokenService.getMallTokenByToken(token);
    	if( null != mallTokenByToken ){
    		Date expiredTime = mallTokenByToken.getExpiredTime();
        	Date now = new Date();
        	if( DateHelper.isGreaterDate(expiredTime, now) ){
        		//根据TOKEN里的userId找到相应 的用户
        		String userId = mallTokenByToken.getUserId();
        		user = mallUserService.get(userId);
        	}
    	}
    	return user;
    }
    
    public MallUser getMallUserByPhone( String phone ){
    	MallUser user = null;
    	MallUserExample example = new MallUserExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andUserPhoneEqualTo(phone);
    	List<MallUser> list = mallUserService.list(example);
    	if( list.size() > 0 ){
    	   user = list.get(0);
    	}
    	return user;
    }
    
    /**
     * 用户默认的头像地址
     * @return
     */
    public String getDefaultHeadImg(){
    	String defaultImg = sysSettingService.getByKey("USER_DEFAULT_IMG");
    	return defaultImg;
    }
    
    /**
     * 判断用户的手机号码与验证码是否一致，且有效没有过期
     * @param phone
     * @param code
     * @return
     */
    public boolean isPhoneCode( String phone, String code ){
    	boolean result = false;
    	PhoneCodeExample example = new PhoneCodeExample();
    	example.setOrderByClause("expired_time desc");
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andPhoneEqualTo(phone).andCodeEqualTo(code);
    	List<PhoneCode> list = phoneCodeService.list(example);
    	if( list.size() > 0 ){
    		PhoneCode phoneCode = list.get(0);
    		Date expiredTime = phoneCode.getExpiredTime();
    		Date now = new Date();
        	if( DateHelper.isGreaterDate(expiredTime, now) ){
        		result = true;
        	}
    	}
    	return result;
    }
    
    public String sendMassageByHuifa( String telphone ){
    	String result = FAIL;
    	   //产生随机的验证码
        String codeCont = "";
	    Random r = new Random();
	    for(int i=0;i<6;i++){
	    	codeCont += String.valueOf(r.nextInt(10));
	    }
	    
	    PhoneCode phoneCode = new PhoneCode();
		phoneCode.setPhone(telphone);
		phoneCode.setCode(codeCont);
		phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
		
	    phoneCodeService.add(phoneCode);
		try {
		
		//String Text=URLEncoder.encode("您的验证码：8859【华信】","utf-8");
				String Text="【友惠家】验证码为：" + codeCont + ",请不要把验证码泄露给其他人,3分钟有效时间！";
				
				String Url="http://dx.ipyy.net/sms.aspx";
				
				HttpClient client=new HttpClient();
						
				PostMethod post=new PostMethod(Url);
				post.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
				NameValuePair userid=new NameValuePair("userid","53772");
				NameValuePair account=new NameValuePair("account","yhjapp");
				NameValuePair password=new NameValuePair("password","123456789");
				NameValuePair mobile=new NameValuePair("mobile",telphone);
				NameValuePair content=new NameValuePair("content",Text);
				NameValuePair sendTime=new NameValuePair("sendTime","");
				NameValuePair action=new NameValuePair("action","send");
				NameValuePair extno=new NameValuePair("extno","");
				post.setRequestBody(new NameValuePair[]{userid,account,password,mobile,content,sendTime,action,extno});
				int statu=client.executeMethod(post);
				System.out.println("statu="+statu);
				String str=post.getResponseBodyAsString();
				
				System.out.println(str);
				
//				HttpMethod method=new PostMethod(Url);//带参数的Url
//				method.setRequestHeader("Content-type", "text/xml; charset=utf-8");
//				client.executeMethod(method);
//				String str = method.getResponseBodyAsString();
//				System.out.println("result="+str);
				
				
					//将字符转化为XML
					Document doc=DocumentHelper.parseText(str);
					//获取根节点
					Element rootElt=doc.getRootElement();
					//获取根节点下的子节点的值
					String returnstatus=rootElt.elementText("returnstatus").trim();
					String message=rootElt.elementText("message").trim();
					String remainpoint=rootElt.elementText("remainpoint").trim();
					String taskID=rootElt.elementText("taskID").trim();
					String successCounts=rootElt.elementText("successCounts").trim();
					
					System.out.println("返回状态为"+returnstatus);
					System.out.println("返回信息提示："+message);
					System.out.println("返回余额："+remainpoint);
					System.out.println("返回任务批次："+taskID);
					System.out.println("返回成功条数："+successCounts);
					if(returnstatus.equals("Success")){
						result = SUCCESS;
					}else{
						result = FAIL;
					}
				} catch (Exception e) {
					
				}
				return result;
    }
    
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassage(String telphone){
    	    String result = null;
    	    //产生随机的验证码
         String codeCont = "";
 	    Random r = new Random();
 	    for(int i=0;i<6;i++){
 	    	codeCont += String.valueOf(r.nextInt(10));
 	    }
 	    
 	    PhoneCode phoneCode = new PhoneCode();
		phoneCode.setPhone(telphone);
		phoneCode.setCode(codeCont);
		phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
		
		String temp = phoneCodeService.add(phoneCode);
 	    
 	    if(ResponseCode.SUCCESS.getCode().equals(temp)){
 	    	HttpClient client = new HttpClient(); 
 			PostMethod method = new PostMethod(Url); 
 				
 			//client.getParams().setContentCharset("GBK");		
 			client.getParams().setContentCharset("UTF-8");
 			method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

 			//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
  		    String content = new String("您的验证码是：【"+codeCont+"】，3分钟有效时间，请不要把验证码泄露给其他人。");
 			// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
  		    NameValuePair[] data = {//提交短信
  				    //new NameValuePair("account", "cf_jdhj"), 
  				    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
  				    new NameValuePair("account", "C11714710"), 
 				    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
  				    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
  				    new NameValuePair("mobile", telphone), 
  				    new NameValuePair("content", content),
  			};
 			
 			method.setRequestBody(data);		
 			
 			
 			try {
 				client.executeMethod(method);	
 				 
 				String SubmitResult =method.getResponseBodyAsString();
 						
 				//System.out.println(SubmitResult);

 				Document doc = DocumentHelper.parseText(SubmitResult); 
 				Element root = doc.getRootElement();


 				String code = root.elementText("code");	
 				//String msg = root.elementText("msg");	
 				//String smsid = root.elementText("smsid");	
 				
 				
 				//System.out.println(code);
 				//System.out.println(msg);
 				//System.out.println(smsid);
 							
 				if("2".equals(code)){
 					result = SUCCESS;
 				}
 				
 			} catch (Exception e) {
 				e.printStackTrace();
 			}	
 	    }
    	
 		return result;
    }
   
    public String getImageServer(){
    	String result = "";
    	sysSettingService.getByKey("");
    	return result;
    }
    
    /**
     * 用户是否领取过红包 
     * @param userId
     * @param productId
     * @return
     */
    public String isHaveHongbao( String userId, String productId ){
    	String result = "0";
    	Product product = productService.get(productId);
    	if( null != product ){
    		HongbaoRecordExample example = new HongbaoRecordExample();
        	Criteria criteria = example.createCriteria();
        	criteria.andIsEffectiveEqualTo(DBConst.TRUE).andUserIdEqualTo(userId).andProductIdEqualTo(productId);
        	criteria.andStartTimeEqualTo(product.getStartTime());
        	criteria.andStopTimeEqualTo(product.getStopTime());
        	List<HongbaoRecord> list = hongbaoRecordService.list(example);
        	if( list.size() > 0 ){
        		result = "1";
        	}
    	}
    	
        return result; 
    }
    
    
    /**
     * 重新过滤红包价格
     * @return
     */
    public String getHongbao( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao();
    	}
    	return result;
    }
    
    
    public String getHongbaoOrder( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		boolean isStart = DateHelper.isGreater( DateHelper.formatDateTime(new Date()),product.getStartTime()+" 00:00:00");
    		if( isStart ){
    			result = product.getProductHongbao();
    		}
    	}
    	return result;
    }
    
    /**
     * 重新过滤红包价格
     * @return
     */
    public String getProdcutPrice( Product product ){
    	String result = "0";
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao();
    	}
    	result = NumberStringHelper.subtractString(product.getProductOrginPrice(),result);
    	return result;
    }
    
    /**
     * 重新过滤红包价格--商品SKU
     * @return
     */
    public String getProdcutSkuPrice( ProductSku sku ){
    	String result = "0";
    	Product product = productService.get(sku.getProductId());
    	boolean greater = DateHelper.isGreater(product.getStopTime()+" 23:59:59", DateHelper.formatDateTime(new Date()));
    	if( greater ){
    		result = product.getProductHongbao();
    	}
    	result = NumberStringHelper.subtractString(sku.getProductOrginPrice(),result);
    	return result;
    }
    
    /**
     * 购物车时用到获得商品价格
     * @param orginPrice
     * @param userId
     * @param product
     * @return
     */
    public String getProductPrice( String orginPrice , String userId, Product product ){
    	String hongbao = "0";
   		if( "1".equals(isHaveHongbao(userId, product.getId())) ){
   			hongbao = getHongbao(product);
   		}
   		hongbao = NumberStringHelper.subtractString(orginPrice, hongbao);
   		return hongbao;
    }
    
    /**
     * 结算进用到的商品价格
     * @param orginPrice
     * @param userId
     * @param product
     * @return
     */
    public String getProductPriceString( String orginPrice, String userId, Product product ){
    	String hongbao = "0";
    	if( "1".equals(isHaveHongbao(userId, product.getId())) ){
    		hongbao = getHongbao(product);
    	}
    	hongbao = NumberStringHelper.subtractString(orginPrice, hongbao);
   		return hongbao;
    }
    
    /**
     * 用户添加积分
     * @param user
     * @param jf
     * @return
     */
    public MallUser userAddJifeng(  MallUser user, int jf ){
    	int userJifeng = 0;
    	if( null != user.getJifeng() ){
    		userJifeng = user.getJifeng();
    	}
    	user.setJifeng(userJifeng+jf);
    	return user;
    }
    
    /**
     * 用户减少积分
     * @param user
     * @param jf
     * @return
     */
    public MallUser userSubJifeng(  MallUser user, int jf ){
    	int userJifeng = 0;
    	if( null != user.getJifeng() ){
    		userJifeng = user.getJifeng();
    	}
    	user.setJifeng(userJifeng-jf);
    	return user;
    }
    
    /**
     * 添加积分
     * @param user
     * @param jf
     * @param note
     * @return
     */
    public Jifeng jifengAdd( MallUser user,int jf, String note ){
    	
    	Jifeng jifeng = new Jifeng();
    	jifeng.setId(IdGen.uuid());
    	jifeng.setIsEffective(DBConst.TRUE);
    	jifeng.setOrgCode(ORG_CODE);
    	jifeng.setCreateTime(new Date());
    	jifeng.setUpdateTime(new Date());
    	jifeng.setCreateUser(CREATE_USER);
    	
    	jifeng.setUserId(user.getId());
    	jifeng.setNote(note);
    	jifeng.setIsAdd("001");
    	jifeng.setJifeng(jf);
    	return jifeng;
    }
    
    /**
     * 减少积分
     * @param user
     * @param jf
     * @param note
     * @return
     */
    public Jifeng jifengSub( MallUser user,int jf, String note ){
    	
    	Jifeng jifeng = new Jifeng();
    	jifeng.setId(IdGen.uuid());
    	jifeng.setIsEffective(DBConst.TRUE);
    	jifeng.setOrgCode(ORG_CODE);
    	jifeng.setCreateTime(new Date());
    	jifeng.setUpdateTime(new Date());
    	jifeng.setCreateUser(CREATE_USER);
    	
    	jifeng.setUserId(user.getId());
    	jifeng.setNote(note);
    	jifeng.setIsAdd("002");
    	jifeng.setJifeng(jf);
    	return jifeng;
    }
    
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public Product filterSeckillPriceDetail( Product product ){
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				//product.setProductOrginPrice(product.getSeckillPrice());
    				product.setProductPrice(product.getSeckillPrice());
    			}
    		}
    	}
        return product;
    }
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public ProductSku filterSkuSeckillPriceDetail( ProductSku productSku ){
    	Product product = productService.get(productSku.getProductId());
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				//product.setProductOrginPrice(product.getSeckillPrice());
    				//product.setProductPrice(product.getSeckillPrice());
    				productSku.setProductPrice(product.getSeckillPrice());
    			}
    		}
    	}
        return productSku;
    }
    
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public String isfilterSeckillPriceDetail( Product product ){
    	String result = "0";
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				result = "1";
    			}
    		}
    	}
        return result;
    }
    
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public String isfilterSeckillPriceDetailNew( Product product ){
    	String result = "0";
    	if( !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType()) ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		split[0]=split[0].replaceAll(":", "");
    		split[1]=split[1].replaceAll(":", "");
    		String start = split[0]+"00";
    		String end =  split[1]+"59";
    		String now = DateHelper.getTime();
    		now=now.replaceAll(":", "");
    		if(Integer.parseInt(now)>Integer.parseInt(start) && Integer.parseInt(end)>Integer.parseInt(now) ){
    			result = "1";
    		}
    		
    	}
        return result;
    }
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public ProductSku filterSeckillPriceDetail( ProductSku productSku ){
    	
    	Product product = productService.get(productSku.getProductId());
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				//productSku.setProductOrginPrice(product.getSeckillPrice());
    				product.setProductPrice(product.getSeckillPrice());
    			}
    		}
    	}
        return productSku;
    }
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public Product filterSeckillPrice( Product product ){
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				product.setProductPrice(product.getSeckillPrice());
    			}
    		}
    	}
        return product;
    }
    
    /**
     * 获取秒杀价格
     * @param product
     * @return
     */
    public ProductSku filterSeckillPrice( ProductSku productSku ){
    	
    	Product product = productService.get(productSku.getProductId());
    	if(  !"none".equals(product.getSeckillType()) && StringHelper.isNotBlank(product.getSeckillType())  ){
    		//判断 是不是在当前时间
    		String nameByCode = outCommonService.getNameByCode("T_DM_MALL_SECKILL_TIME", product.getSeckillType());
    		String[] split = nameByCode.split("~");
    		String date = DateHelper.getDate("yyy-MM-dd");
    		
    		String start = date + " " + split[0]+":00";
    		String end = date + " " + split[1]+":00";
    		
    		String now = date + " " + DateHelper.getTime();
    		boolean greater = DateHelper.isGreater(now, start);
    		if( greater ){
    			boolean greater2 = DateHelper.isGreater(end, now);
    			if( greater2 ){
    				productSku.setProductPrice(product.getSeckillPrice());
    			}
    		}
    	}
        return productSku;
    }
    
    /**
     * 过滤用户的价格
     * @param user
     * @param product
     * @return
     */
    public Product filterPriceByUser( MallUser user, Product product ){
    	//重置设置红包金额
    	String hongbao = "0";
    	if( "1".equals(isHaveHongbao(user.getId(), product.getId())) ){
    		hongbao = getHongbaoOrder(product);
    		product.setProductHongbao(hongbao);
    	}
    	//重置productPrice
    	String productPrice = NumberStringHelper.subtractString(product.getProductOrginPrice(), hongbao);
    	product.setProductPrice(productPrice);
    	//是否为秒杀时段
    	return filterSeckillPrice(product);
    }
    
    /**
     * 过滤普通价格
     * @param product
     * @return
     */
    public Product filterPrice( Product product ){
    	String hongbao = getHongbao(product);
		product.setProductHongbao(hongbao);
		//重置productPrice
    	String productPrice = NumberStringHelper.subtractString(product.getProductOrginPrice(), hongbao);
    	product.setProductPrice(productPrice);
    	return product;
    }
    
    
    /**
     * 过滤用户的价格
     * @param user
     * @param product
     * @return
     */
    public ProductSku filterSkuPriceByUser( MallUser user, ProductSku productSku ){
    	//重置设置红包金额
    	String hongbao = "0";
    	Product product = productService.get(productSku.getProductId());
    	
    	if( "1".equals(isHaveHongbao(user.getId(), product.getId())) ){
    		hongbao = getHongbaoOrder(product);
    		productSku.setProductHongbao(hongbao);
    	}
    	//重置productPrice
    	String productPrice = NumberStringHelper.subtractString(productSku.getProductOrginPrice(), hongbao);
    	productSku.setProductPrice(productPrice);
    	//是否为秒杀时段
    	return productSku;
    }
    
    /**
     * 过滤普通价格
     * @param product
     * @return
     */
    public ProductSku filterSkuPrice( ProductSku productSku ){
    	Product product = productService.get(productSku.getProductId());
    	String hongbao = getHongbao(product);
    	
		productSku.setProductHongbao(hongbao);
		//重置productPrice
    	String productPrice = NumberStringHelper.subtractString(productSku.getProductOrginPrice(), hongbao);
    	productSku.setProductPrice(productPrice);
    	return filterSeckillPrice(productSku);
    }
    
    
    public String paySuccess( Order order, String payType ){
    	
    	String orderId = order.getId();//获取订单ID

	    List<MarketUser> marketUsers = new ArrayList<MarketUser>();//是否存在商家 ID
		List<PreMoney> preMoneys = new ArrayList<PreMoney>();//预计收益信息
		List<OrderProducts> products = new ArrayList<OrderProducts>();
		OrderPay orderPay = null;//支付信息
		
		//获取云店主信息
		MallUser mallUser = mallUserService.get(order.getUserId());
		MarketUser marketUser = getMarketUserByMallUser(mallUser);
		
		order.setPayTime(DateHelper.getDateTime());//设置订单支付时间
		order.setPayType(payType);//更新订单支付类型
		order.setStatus("1");//改变订单为已支付状态
		
		//将该订单下的商品项状态全部更新为支付状态 
		OrderProductsExample example = new OrderProductsExample();
		example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderIdEqualTo(orderId);
		products = orderProductsService.list(example);
		
		String totalProfit = "0";//该笔订单总佣金
		
		for( OrderProducts ttmp: products ){
			ttmp.setStatus("1");//状态为支付状态
			ttmp.setBackStatus("0");//退换货的字段
			Product product = productService.get(ttmp.getProductId());	//获取商品信息	
			//商品佣金是否有
			if( StringHelper.isNotBlank(product.getMarketProfitPercent()) && !"0".equals(product.getMarketProfit()) ){
				//根据商品的佣金比例算出商品多少佣金
				String tempProfit = NumberStringHelper.mulString(product.getMarketProfitPercent().replace("%", ""), ttmp.getTotalMoney());
				tempProfit = NumberStringHelper.divString(tempProfit, "100", 2);
				//添加预计收益信息
				if( NumberStringHelper.isGreaterNoEqual(tempProfit, "0") ){
					
					PreMoney preMoney = new PreMoney();//预计收益信息
					//六个必填字段
					preMoney.setId(IdGen.uuid());
					preMoney.setIsEffective(DBConst.TRUE);
					preMoney.setCreateTime(new Date());
					preMoney.setUpdateTime(new Date());
					preMoney.setCreateUser(CREATE_USER);
					preMoney.setOrgCode(ORG_CODE);
				
					//关联字段
					preMoney.setNote("VIP用户“"+filterEmoji(mallUser.getUserNickName())+"”购买商品《"+product.getName()+"》已成功付款，预计收益"+tempProfit+"元！");
					
					preMoney.setMarketUserId(marketUser.getId());
					//业务字段
					preMoney.setPreMoney(tempProfit);
					preMoney.setIsGive(DBConst.FALSE);
					preMoney.setIsCancel(DBConst.FALSE);
					preMoney.setOrderId(order.getId());
					preMoney.setOrderNum(order.getOrderNum());
					preMoney.setOrderTotalMoney(order.getTotalMoney());
					preMoney.setOrderDate( DateHelper.getDateByStringDate(order.getPayTime()) );
					
					preMoney.setOrderProductsId(ttmp.getId());
					preMoney.setProductSkuId(ttmp.getPropertySkuId());
					preMoney.setProductId(ttmp.getProductId());
					preMoneys.add(preMoney);
					
					//将总佣金添加
					totalProfit = NumberStringHelper.addString(totalProfit, tempProfit);
				}
			}
			
		}
		
		//将云店的预计收益添加
		String preProfit = "0";
		if( StringHelper.isNotBlank( marketUser.getPreProfit()) ){
			preProfit = marketUser.getPreProfit();
		}
		preProfit=NumberStringHelper.addString(preProfit, totalProfit);
		marketUser.setPreProfit(preProfit);
		marketUsers.add(marketUser);
		
		//添加支付信息
	    orderPay = new OrderPay();
	    //六个必填字段
	    orderPay.setId(IdGen.uuid());
	    orderPay.setIsEffective(DBConst.TRUE);
	    orderPay.setCreateTime(new Date());
	    orderPay.setUpdateTime(new Date());
	    orderPay.setCreateUser(CREATE_USER);
	    orderPay.setOrgCode(ORG_CODE);
	    //关联字段
	    orderPay.setUserId(order.getUserId());
	    //业务字段
		orderPay.setPayOrderNum(order.getOrderNum());
		orderPay.setPayStatus("支付成功");
		orderPay.setPayTime( DateHelper.getDateTime());
		orderPay.setPayType(payType);
		orderPay.setTotalMoney(order.getTotalMoney());
		
		//添加用户积分
		Double jf = Double.parseDouble(order.getTotalMoney());
		int intValue = jf.intValue();
		mallUser = userAddJifeng(mallUser,intValue);
		
	    Jifeng jifeng = jifengAdd( mallUser, intValue, "vip用户购买商品"+payType+"支付"+order.getTotalMoney()+"元，获得积分"+order.getTotalMoney() );
				
		//同步数据库更新操作
		return orderService.paySuccessV2(marketUsers,preMoneys,order,products,orderPay,mallUser,jifeng);
   
    }
    
    protected MarketUser getMarketUserByMallUser( MallUser mallUser ){
    	//判断 用户本身是否为云店主
    	MarketUser marketuser = marketUserService.getByUnionid(mallUser.getUnionId());
    	if( marketuser == null ){
    		String yunId = "0";
    		if( StringHelper.isNotBlank(mallUser.getYunId()) && !"null".equals(mallUser.getYunId()) ){
    			yunId = mallUser.getYunId();
    		}else{
    			yunId = sysSettingService.getByKey("YUN_ZHU_ID");
    		}
    		marketuser = marketUserService.get(yunId);
    	}
		
		return marketuser;
    }
    
    protected String getYunIdByUser( MallUser mallUser ){
    	String result = "0";
    	if( mallUser != null ){
    		if( StringHelper.isNotBlank(mallUser.getYunId()) && !"null".equals(mallUser.getYunId()) ){
    			result = mallUser.getYunId();
    		}else{
    			result = sysSettingService.getByKey("YUN_ZHU_ID");
    		}
    	}
    	return result;
    }
    
    
    protected void deleteProductJd( String id ){
    	ProductJd temp = new ProductJd();
    	temp.setId(id);
    	temp.setIsEffective(DBConst.FALSE);
    	productJdService.edit(temp);
    	
    	MarketUserProductExample example = new MarketUserProductExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andProductIdEqualTo(id);
    	
    	MarketUserProduct userProduct = new MarketUserProduct();
    	userProduct.setIsEffective(DBConst.FALSE);
    	
    	marketUserProductService.deleteByExample(userProduct, example);
    }
    
    
    public static String filterEmoji(String source) { 
    	String result = "";
        if(source != null)
        {
            Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
            Matcher emojiMatcher = emoji.matcher(source);
            if ( emojiMatcher.find())
            {
                result = emojiMatcher.replaceAll("*");
            }
       }
       result = result.replace("*", "");
       result =result.replace(" ", "");
       return result; 
    }
    
    
    public void jdCountStatics( String userId, String returnStatus,String sku ){
    	ProductJdStatisExample example = new ProductJdStatisExample();
    	com.itic.mall.system.productjdstatis.persistence.model.ProductJdStatisExample.Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	//开始时间
    	String startStr = DateHelper.formatDate(new Date(), "yyyy-MM-dd");
    	startStr = startStr + " 00:00:00";
    	Date startTime = DateHelper.getDateByStringDate(startStr);
    	criteria.andCreateTimeBetween(startTime, new Date());
    	
    	int reorder = productJdStaticService.count(example);
    	
    	ProductJdStatis statis = new ProductJdStatis();
    	statis.setReorder(reorder+1);
    	statis.setUserName(userId);
    	statis.setProductSku(sku);
    	statis.setReturnStatus(returnStatus);
    	statis.setNote("用户点击查看京东商品信息");
    	productJdStaticService.add(statis);
    }
    
    
    public String getTgwIdByTgwName( String tgwName ){
    	String result = "";
    	if( StringHelper.isNotBlank(tgwName) ){
    		SyncTgw temp = syncTgwService.getByTgwName(tgwName);
    		if( null != temp ){
    			result = temp.getTgwId();
    		}
    	}
    	return result;
    }
    
    /**
     * isOneOrder
     * @param userid
     * @return
     */
    public boolean isOneOrder( String userid ){
    	boolean result = false;
    	OrderExample example = new OrderExample();
   		com.itic.mall.system.order.persistence.model.OrderExample.Criteria criteria = example.createCriteria();
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		criteria.andUserIdEqualTo(userid);
   		//criteria.andPayTimeIsNotNull();
   		List<Order> list = orderService.list(example);
        if( list.size()==0 ){
        	result = true;
        }
        return result;
    }
    
    /**
     * 获取推广位ID信息
     * @param userid
     * @return
     */
    public String getTgwidByUserid( String userid ){
    	String result = "";
    	if( StringHelper.isNotBlank(userid) ){
    		//根据用户获取推广位id
    		result = syncTgwService.getTgwidByUserid(userid);
    	}
    	return result;
    }
    
    /**
     * 根据推广位获取二合一转链接
     * @param userid
     * @param skuId
     * @param conUrlB
     * @return
     */
    public String getConUrl( String pid, String skuId, String conUrlB ){
    	String result = "";
    	if( StringHelper.isNotBlank(conUrlB) && StringHelper.isNotBlank(skuId) ){
    		result = productJdService.getConLinkByDdt(skuId,conUrlB,pid);
    	}
    	return result;
    }
    
    /**
     * 根据推广位获取二合一转链接
     * @param userid
     * @param skuId
     * @param conUrlB
     * @return
     */
    public String getCommonUrl( String pid, String skuId ){
    	String result = "";
    	if( StringHelper.isNotBlank(skuId) ){
    		result = productJdService.getCommonLinkByDdt( skuId,pid );
    	}
    	return result;
    }
}